package com.andrew.dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.eclipse.jdt.internal.compiler.ast.QualifiedAllocationExpression;

import com.andrew.dao.CustomerDao;
import com.andrew.entity.Cart;
import com.andrew.entity.Customer;
import com.andrew.util.JDBCUtils;
import com.sun.org.apache.bcel.internal.generic.NEW;

public class CustomerDaoImpl implements CustomerDao{

	@Override
	public Customer findCustomer(String phone, String password) throws SQLException {
		//获取连接池
		DataSource dataSource = JDBCUtils.getDataSource();
		
		//新建一个执行对象
		QueryRunner qr=new QueryRunner(dataSource);
		
		//执行sql语句并封装到JavaBean对象中
		String sql="SELECT * FROM Customer WHERE Telephone=? and PASSWORD=?";
		Customer customer= qr.query(sql, new BeanHandler<Customer>(Customer.class),phone,password);
		
		//返回这个对象
		return customer;
	}
	/***
	 * insertCustomer
	 * param:连接对象，用户对象
	 * return: int 修改的行数
	 */
	@Override
	public int InsertCustomer(Connection conn,Customer customer) throws SQLException {
		QueryRunner qr=new QueryRunner();
		String sql="INSERT INTO Customer VALUES('0',?,?,?,?,?,?,0,0.0)";
		
		return qr.update(conn,sql,customer.getUserName(),customer.getRealName(),customer.getGender(),customer.getIDNumber(),customer.getTelephone(),customer.getPASSWORD());
	}

	/***
	 * insertCart
	 * params:连接对象，用户对象
	 * return：int 修改行数
	 */
	@Override
	public int InsertCart(Connection conn, Customer customer) throws SQLException {
		// TODO Auto-generated method stub
		
		QueryRunner qr=new QueryRunner();
		String sql="INSERT INTO Cart VALUES('0',(SELECT CustomerId FROM Customer where username='"+customer.getUserName()+"'))";
		return qr.update(conn,sql);
	}
	/**
	 *通过用户id获得用户 
	 */
	@Override
	public Customer findCustomer(int customerId) throws SQLException {
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		return qr.query("select * from Customer where CustomerId=?",new BeanHandler<Customer>(Customer.class),customerId);
	}
	@Override
	public List<Customer> findAllCustomer() throws SQLException {
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		List<Customer> allCustomers=qr.query("select * from Customer",new BeanListHandler<Customer>(Customer.class));
		return allCustomers;
	}
	@Override
	public List<Customer> findAllCommonCustomer() throws SQLException {
		QueryRunner qr=new QueryRunner(JDBCUtils.getDataSource());
		List<Customer> allCustomers=qr.query("select * from Customer where isAdmin=0",new BeanListHandler<Customer>(Customer.class));
		return allCustomers;
	}
	



}